package com.liujit.standard.basis.core.factory;

import com.liujit.standard.basis.core.annotation.Trimmed;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;

import java.text.ParseException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

/**
 * @Description 去除前后空格的注解格式工厂类
 * @Author tjf
 * @Date 2020-09-28 11:05
 * @Version 1.0
 */
public class TrimmedAnnotationFormatterFactory implements AnnotationFormatterFactory<Trimmed> {
    @Override
    public Set<Class<?>> getFieldTypes() {
        Set<Class<?>> fieldTypes = new HashSet<>(1,1);
        fieldTypes.add(String.class);
        return fieldTypes;
    }

    @Override
    public Printer<?> getPrinter(Trimmed trimmed, Class<?> aClass) {
        return new TrimmedFormatter();
    }

    @Override
    public Parser<?> getParser(Trimmed trimmed, Class<?> aClass) {
        return new TrimmedFormatter();
    }

    private static class TrimmedFormatter implements Formatter<String>{

        @Override
        public String parse(String s, Locale locale) throws ParseException {
            return s.trim();
        }

        @Override
        public String print(String s, Locale locale) {
            return s;
        }
    }

}
